import { RouteRecordRaw } from 'vue-router';
import { IBreadCrumb } from '@/components/NaVHeader/type';

let firstRoute: any = null;
export const mapMenusToRoutes = function (userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = [];
  const allRoutes: RouteRecordRaw[] = [];

  // require.context(arg1, arg2, arg3);
  /*
    arg1: string,  path;
    arg2: boolean, 是否递归寻找文件;
    arg3: regexp, 正则匹配(文件名);
  */
  const routeFiles = require.context('@/router/main', true, /\.ts$/);

  routeFiles.keys().forEach((key) => {
    // key:  ./analysis/dashboard/dashboard.ts

    const route = require('@/router/main' + key.slice(1)).default;

    allRoutes.push(route);
  });

  /*
    userMenus:
      type === 1  -> 取 children
      type === 2 -> 匹配 route
  */

  const recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      const { type, children, url } = menu;

      if (type === 2) {
        const route = allRoutes.find((o) => o.path === url);
        if (route) {
          !firstRoute && (firstRoute = route);
          routes.push(route);
        }
      } else {
        children && children.length && recurseGetRoute(children);
      }
    }
  };
  recurseGetRoute(userMenus);

  return routes;
};

export const searchBreadCrumbs = function (
  userMenus: any[],
  path: string
): IBreadCrumb[] {
  const breakCrumb: IBreadCrumb[] = [];

  searchMenuIdByPath(userMenus, path, breakCrumb);

  return breakCrumb;
};

export const searchMenuIdByPath = function (
  userMenus: any[],
  path: string,
  breadCrumbs?: IBreadCrumb[]
): any {
  for (const menu of userMenus) {
    const type = menu.type;
    if (type === 1) {
      const fMenu = searchMenuIdByPath(menu.children ?? [], path);
      if (fMenu) {
        if (breadCrumbs) {
          breadCrumbs.push({ name: menu.name });
          breadCrumbs.push({ name: fMenu.name, path: fMenu.url });
        }
        return searchMenuIdByPath(menu.children ?? [], path);
      }
    } else if (type === 2 && menu.url === path) {
      return menu;
    }
  }
};

export const mapMenusToPermission = function (userMenus: any[]) {
  const permissions: string[] = [];

  const recurseGetPermission = (menus: any[]) => {
    for (const menu of menus) {
      const type = menu.type;
      if ([1, 2].includes(type)) {
        recurseGetPermission(menu.children ?? []);
      } else if (type === 3) {
        permissions.push(menu.permission);
      }
    }
  };

  recurseGetPermission(userMenus);

  return permissions;
};

export { firstRoute };
